/*
 * Copyright (C) 2010 The Android Open Source Project 
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at 
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software 
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and 
 * limitations under the License.
 */

package org.lhlzi.ithink;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import org.lhlzi.ithink.R;
import org.lhlzi.widget.TabActivity;
import org.lhlzi.widget.TabHost;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences.Editor;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.text.Html;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.Window;

public class ThinkingCaller extends TabActivity{

	public static final String TAG = ThinkingCaller.class.toString();
	
	private static TabHost mTabs = null;
	
	private static final String ACTION_MAIN = "android.intent.action.MAIN";
	private static final String ACTION_CALL_BUTTON = "android.intent.action.CALL_BUTTON";
	private static final String ACTION_VIEW = "android.intent.action.VIEW";
	
	public final static String FAVORITES = "favorites";
	public final static String RECENTS = "recents";
	public final static String CONTACTS = "contacts";
	public final static String KEYPAD = "keypad";
	public final static String VOICEMAIL = "voicemail";
	
	private static final int MENU_PREFERENCES = 10;
	
	private static final int DIALOG_FIRST_TIME = 21;
	private static final int DIALOG_CHANGELOG = 22;
	private static final int DIALOG_UNINSTALL = 23;
	
	

	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		
		super.onCreate(savedInstanceState);
		
		
		
		if (Utils.isInProMode(this)) {
			
			showDialog(DIALOG_UNINSTALL);
			
		
//			Uri uri = Uri.fromParts("package", "org.lhlzi.icaller", null);  
//			Intent it = new Intent(Intent.ACTION_DELETE, uri);    
//			startActivity(it);  
			
			return;
		}
		
		String version = null;
		
		try {
			version = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
		}
		
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
		Editor editor = prefs.edit();
		
		String prefsVersion = prefs.getString("", null);
		
		if (prefsVersion == null) {
			showDialog(DIALOG_FIRST_TIME);
		}
		
		
		if (!version.equals(prefsVersion)) {
			editor.putString("", version);
			editor.commit();
			showDialog(DIALOG_CHANGELOG);
		}
		
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// Init tab views for TabActivity..
		initTabViews(getIntent().getAction());
		
	}
	
	@Override
	protected void onNewIntent(Intent intent) {
		super.onNewIntent(intent);
		
		Log.i(TAG, "Track activity start. [action=" + intent.getAction() + "]");
		
		if (intent.getAction().equals(ACTION_MAIN)) mTabs.setCurrentTabByTag(KEYPAD);
		else if (intent.getAction().equals(ACTION_CALL_BUTTON) || intent.getAction().equals(ACTION_VIEW))
			mTabs.setCurrentTabByTag(RECENTS);
	}
	
	
	private void initTabViews(String action) {
		
		mTabs = getTabHost();
		
		final Intent intent = new Intent();
		
		if (action.equals(ACTION_VIEW)) {
			
		}
		
		mTabs.addTab(mTabs.newTabSpec(FAVORITES)
					.setIndicator(getString(R.string.dialer_favorites), getResources().getDrawable(R.drawable.favorites))
					.setContent(new Intent(this, Favorites.class)));
		
		mTabs.addTab(mTabs.newTabSpec(RECENTS)
				.setIndicator(getString(R.string.dialer_recents), getResources().getDrawable(R.drawable.recents))
				.setContent(new Intent(this, IphoneCallLogScreen.class)));
		
		mTabs.addTab(mTabs.newTabSpec(CONTACTS)
				.setIndicator(getString(R.string.dialer_contacts), getResources().getDrawable(R.drawable.contacts))
				.setContent(new Intent(this, Contacts.class)));
		
		mTabs.addTab(mTabs.newTabSpec(KEYPAD)
				.setIndicator(getString(R.string.dialer_keypad), getResources().getDrawable(R.drawable.keypad))
				.setContent(new Intent(this, NumberSearch.class)));
		
		
		mTabs.addTab(mTabs.newTabSpec(VOICEMAIL)
				.setIndicator(getString(R.string.dialer_voicemail), getResources().getDrawable(R.drawable.voicemail))
				.setContent(new Intent(this, Voicemails.class)));
		
		if (action.equals(ACTION_MAIN)) mTabs.setCurrentTabByTag(KEYPAD);
		else if (action.equals(ACTION_CALL_BUTTON) || action.equals(ACTION_VIEW))
			mTabs.setCurrentTabByTag(RECENTS);
		
	}
	
	public static void select(int index) {
		if (mTabs == null)
			throw new NullPointerException("Specified object is null");
		
		mTabs.setCurrentTab(index);
	}
	
	public static void selectByTag(String tag) {
		if (mTabs == null)
			throw new NullPointerException("Specified object is null");
		
		mTabs.setCurrentTabByTag(tag);
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
			
		case DIALOG_FIRST_TIME:
			return new AlertDialog.Builder(this)
			.setTitle(R.string.welcome_to_ithink)
			.setMessage(R.string.welcome_to_ithink_msg)
			.setPositiveButton(R.string.close, null)
			.create();
			
		case DIALOG_CHANGELOG:
			StringBuilder changelog = new StringBuilder();
			BufferedReader input;
			try {
				InputStream is = getResources().openRawResource(R.raw.changelog);
				input = new BufferedReader(new InputStreamReader(is));
				String line;
				while ((line = input.readLine()) != null) {
					changelog.append(line);
					changelog.append("<br/>");
				}
				input.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			return new AlertDialog.Builder(this)
			.setTitle(R.string.changelog_title)
			.setMessage(Html.fromHtml(changelog.toString()))
			.setPositiveButton(R.string.close, null)
			.create();
			
		case DIALOG_UNINSTALL:
			return new AlertDialog.Builder(this)
			.setTitle(R.string.uninstall_notice)
			.setMessage(R.string.uninstall_notice_msg)
			.setIcon(android.R.drawable.ic_dialog_alert)
			.setPositiveButton(R.string.close, new OnClickListener(){
				@Override
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
				
			})
			.create();
			
		}
		return null;
	}
	
	@Override
	public boolean onPrepareOptionsMenu(Menu menu) {
		menu.clear();
		menu.add(0, MENU_PREFERENCES, 1, "Preferences").setIcon(
				android.R.drawable.ic_menu_preferences);
		
		
		return super.onPrepareOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		
		switch(item.getItemId()) {
		case MENU_PREFERENCES:
			Intent preferencesIntent = new Intent (this,
					org.lhlzi.ithink.Preferences.class);
			startActivity(preferencesIntent);
			return true;
		}
		
		return super.onOptionsItemSelected(item);
		
	}
}
